/*******************************************************************************
 * Copyright (c) 2011 LegSem.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * 
 * Contributors:
 *     LegSem - initial API and implementation
 ******************************************************************************/
package com.legsem.legstar.jca;

import javax.resource.ResourceException;
import javax.resource.spi.ConnectionEvent;
import javax.resource.spi.ConnectionEventListener;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * In a non managed environment (typically for testing), this provides a default
 * connection manager without pooling.
 * 
 */
public class LegStarDefaultConnectionManager implements ConnectionManager,
        ConnectionEventListener {

    private static final long serialVersionUID = 7814850251552428983L;

    /** Logger. */
    private final Log log = LogFactory.getLog(getClass());

    public Object allocateConnection(ManagedConnectionFactory mcf,
            ConnectionRequestInfo cxRequestInfo) throws ResourceException {
        ManagedConnection mc = mcf.createManagedConnection(null, cxRequestInfo);
        mc.addConnectionEventListener(this);
        return mc.getConnection(null, cxRequestInfo);
    }

    public void connectionClosed(ConnectionEvent event) {
        try {
            ((ManagedConnection) event.getSource()).destroy();
        } catch (ResourceException e) {
            log.error("Failed to destroy connection.", e);
        }
    }

    public void localTransactionStarted(ConnectionEvent event) {

    }

    public void localTransactionCommitted(ConnectionEvent event) {

    }

    public void localTransactionRolledback(ConnectionEvent event) {

    }

    public void connectionErrorOccurred(ConnectionEvent event) {
        try {
            ((ManagedConnection) event.getSource()).destroy();
        } catch (ResourceException e) {
            log.error("Failed to destroy connection.", e);
        }
    }

}
